package edu.njfu.mystudentapp

import android.app.AlertDialog
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import edu.njfu.mystudentapp.model.ResultVO
import edu.njfu.mystudentapp.service.StudentService
import edu.njfu.mystudentapp.utils.ServerCreator
import kotlinx.android.synthetic.main.activity_register.*

class RegisterActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        var intent: Intent
        setContentView(R.layout.activity_register)
        RegisterBtn.setOnClickListener{
            var acount=RegisterAccount.text.toString()
            var password=RegisterPassword.text.toString()
            var password2=RegisterPassword2.text.toString()
            if(password==password2){
                val studentService= ServerCreator.create(StudentService::class.java)
                studentService.registerUser(RegisterAccount.text.toString(),RegisterPassword.text.toString()).enqueue(object :retrofit2.Callback<ResultVO>{
                    override fun onFailure(call: retrofit2.Call<ResultVO>, t: Throwable) {
                        Toast.makeText(this@RegisterActivity,"无法连接网络",Toast.LENGTH_SHORT).show()

                    }

                    override fun onResponse(
                        call: retrofit2.Call<ResultVO>,
                        response: retrofit2.Response<ResultVO>
                    ) {
                        var resultVO=response.body()
                        if(resultVO?.result.toString()=="ok"){

                            Toast.makeText(this@RegisterActivity,"注册成功", Toast.LENGTH_LONG).show()
                            intent= Intent(this@RegisterActivity,MainActivity::class.java)
                            intent.putExtra("account",acount)
                            intent.putExtra("password",password)

                            startActivity(intent)

                        }else{
                            AlertDialog.Builder(this@RegisterActivity).apply {

                                setTitle("注册失败")
                                setMessage("已存在账号")
                                setCancelable(false)
                                setPositiveButton("ok"){
                                        dialog, which ->
                                }
                                show()
                            }
                        }
                    }
                })
            }else{
                Toast.makeText(this,"密码不相同", Toast.LENGTH_LONG).show()
            }
        }
    }
}